import React, { PureComponent } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  message,
  Button,
  Table,
  Modal,
  Form,
  Input,
  Popconfirm,
  Divider
} from 'antd'
import { connect } from 'dva'
import {LZFormItem} from "@/components/LZForm";
import departmentService from "@/services/department";
import {router} from "umi";

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
}

@connect()
@Form.create()
class TabSetting extends PureComponent {
  state = {
    title: '',//modal的标题
    imgSrc: '',
    fileList: [],
    pageNumber: 1,
    pageSize: 10,
    visible: false,
    loading: true,
    addConfirmLoading: false,
    tableData: [],
    detail: {},
    departments: []
  }

  columns = [
    {
      title: '部门名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '职能描述',
      dataIndex: 'description',
      align: 'center',
    },
    {
      title: '成员数量',
      dataIndex: 'userCount',
      align: 'center',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      align: 'center',
      key: 'createTime',
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text, record) => (
        <div className="table-action">
          <a onClick={() => this.edit(record)}>修改</a>
          <Divider type="vertical" />
          <a onClick={() => this.editPermission(record)}>权限设置</a>
          <Divider type="vertical" />
          <Popconfirm
            title='确定要删除吗？'
            onConfirm={() => this.deleteItem(record)}
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      )
    },
  ]

  componentDidMount() {
    this.initData();
  }

  add = () => {
    this.setState({
      visible: true,
      title: '新增部门',
      detail: {}
    })
  }

  deleteItem = (record) => {
    departmentService.delete({
      id: record.id
    }).then(res => {
      message.success('删除成功')
      this.initData()
    })
  }

  edit = (record) => {
    this.setState({
      visible: true,
      detail: record,
      title: '修改部门'
    })
  }

  editPermission = (record) => {
    router.push('/permission/index/config/department-'+record.id)
  }

  close = () => {
    this.setState({
      visible: false
    })
  }

  initData = () => {
    let payload = {
      pageNumber: this.state.pageNumber,
      pageSize: this.state.pageSize,
    };
    this.setState(
      {
        loading: true,
      },
      () => {
        departmentService.queryPage(payload).then(res=>{
          message.success('获取信息成功');
          this.setState({
            tableData: res.records,
            total: res.total,
            loading: false,
            current: res.current,
          });
        }).catch(err=>{
          this.setState({
            loading: false
          });
        })
      },
    );
  };

  handleOk = () => {
    debugger
    const { title, detail } = this.state
    const { form, } = this.props
    form.validateFields((err, values) => {
      if (!err) {
        const params = values || {};
        for (const key in params) {
          if (typeof params[key] === 'string') {
            params[key] = params[key].trim();
          }
        }
        const service = title === '新增部门'? departmentService.add : departmentService.update
        service({
          ...params,
          id: detail.id,
        }).then(res => {
          this.handleFilter()
          message.success('保存成功')
        }).finally(() => {
          this.close()
        })
      }
    });
  }

  handleFilter = (data = {}) => {
    if (data.queryType && data.queryType === '分页') {
      this.initData();
    } else {
      this.setState(
        {
          pageNumber: 1,
          pageSize: 10,
          memberName: data.memberName ? data.memberName : null,
          departments: data.departments ? data.departments : null,
        },
        () => {
          this.initData();
        },
      );
    }
  };

  //分页，下一页
  onChange = pageNumber => {
    this.setState({
      pageNumber: pageNumber,
    }, () => {
      this.getProduct()
    })
  }
  showTotal = () => {
    return `共有${this.state.total}条`
  }
  //切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState({
      pageSize: pageSize,
      pageNumber: 1,
    }, () => {
      this.getProduct()
    })
  }

  render() {
    const {
      loading, visible, addConfirmLoading,current, total, tableData, detail, title
    } = this.state;
    const { getFieldDecorator } = this.props.form
    const { name, description,  } = detail;

    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Button type='primary' className="mt-20 mb-18 w-112" onClick={this.add}>新增部门</Button>
          <Table
            loading={loading}
            columns={this.columns}
            dataSource={tableData}
            rowKey={record => record.id}
            pagination={{
              current: current,
              total: total,
              onChange: this.onChange,
              showTotal: this.showTotal,
              showQuickJumper: true,
              pageSizeOptions: ['3', '5', '10'],
              showSizeChanger: true,
              onShowSizeChange: this.onShowSizeChange,
            }}
          >
          </Table>
        </Card>
        {/* 新增 */}
        <Modal
          title={title}
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={addConfirmLoading}
          destroyOnClose={true}
          onCancel={() => {
            this.setState({
              visible: false,
              fileList: [],
              imgSrc: '',
            })
          }}
        >
          <Form
            {...formItemLayout}
          >
            <LZFormItem field="name" label="部门名称" getFieldDecorator={getFieldDecorator}
                        requiredMessage="部门名称不能为空"
                        pattern={/^[^\s]*$/}
                        initialValue={name}>
              <Input placeholder='请输入'/>
            </LZFormItem>
            <LZFormItem label="职能描述" field="description" getFieldDecorator={getFieldDecorator}
                        initialValue={description} requiredMessage="职能描述不能为空" pattern={/^[^\s]*$/}>
              <Input.TextArea rows={4} placeholder="请输入职能描述" />
            </LZFormItem>

          </Form>
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default TabSetting
